$('#exampleModalChange').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var recipient = button.data('whatever');
    var rezijie = button.data('zijie');
    var modal = $(this);
    console.log(recipient)
    if(recipient != 0 && recipient != undefined){
        var data = {
            id:recipient
        }
        $.ajax({
            url: '/admin/auth/index',
            data:data,
            type: 'POST',
            dataType: 'json'
        }).done(function(response) {
            modal.find('.modal-title').text('编辑' + response.data.title);
            //下拉选择
            var s = document.getElementById("pid");
            var ops = s.options;
            for(var i=0;i<ops.length; i++){
                var tempValue = ops[i].value;
                if(tempValue == response.data.pid)   //这里是你要选的值
                {
                    ops[i].selected = true;
                    break;
                }
            }
            modal.find('.modal-body [name=id]').val(recipient);
            modal.find('.modal-body [name=title]').val(response.data.title);
            modal.find('.modal-body [name=name]').val(response.data.name);
            modal.find('.modal-body [name=icon]').val(response.data.icon);
            modal.find('.modal-body [name=weight]').val(response.data.weight);
            //单选
            var ds = document.getElementsByName("ismenu");
            console.log(ds);
            //var opds = ds.options;
            for(var i1=0;i1<ds.length; i1++){
                var dtempValue = ds[i1].value;
                if(dtempValue == response.data.ismenu)   //这里是你要选的值
                {
                    ds[i1].checked  = true;
                    break;
                }
            }
            var ds1 = document.getElementsByName("isnav");
            console.log(ds1);
            //var opds = ds.options;
            for(var i2=0;i2<ds1.length; i2++){
                var dtempValue2 = ds1[i2].value;
                if(dtempValue2 == response.data.isnav)   //这里是你要选的值
                {
                    ds1[i2].checked  = true;
                    break;
                }
            }

        }).fail(function() {
            console.error('数据错误');
        });
    }else if(recipient == 0 && recipient != undefined) {
        modal.find('.modal-title').text('新增规则');
        modal.find('.modal-body [name=id]').val('');
        $("#pid").val('0');
        modal.find('.modal-body [name=title]').val('');
        modal.find('.modal-body [name=name]').val('');
        modal.find('.modal-body [name=icon]').val('');
        modal.find('.modal-body [name=weight]').val('');
    }else if(recipient == undefined && rezijie > 0) {
        console.log('rezijie:'+rezijie)
        modal.find('.modal-body [name=id]').val('');
        modal.find('.modal-body [name=title]').val('');
        modal.find('.modal-body [name=name]').val('');
        modal.find('.modal-body [name=icon]').val('');
        modal.find('.modal-body [name=weight]').val('');
        $("#pid").val(rezijie);
    }
})

// tree-grid使用
var $treeTable = $('.tree-table');
$treeTable.bootstrapTable({
    url: '/admin/auth/datalist',
    method: 'get',
    idField: 'id',
    uniqueId: 'id',
    dataType: 'json',
    toolbar: '#toolbar2',
    columns: [
        {
            field: 'check',
            checkbox: true
        },
        {
            field: 'title',
            title: '规则名称'
        },
        {
            field: 'name',
            title: '规则URL'
        },
        {
            field: 'weight',
            title: '排序权重'
        },
        {
            field: 'icon',
            title: '菜单图标',
            formatter: function(value, row, index) {
                result = '<span class="'+ value+ '"></span>';

                return result;
            },
        },
        {
            field: 'ismenu',
            title: '规则类型',
            formatter: function(value, row, index) {
                if(value == 0){
                    result = '<a href="#!" class="badge badge-primary">链接</a>'
                }else if (value == 1){
                    result = '<a href="#!" class="badge badge-success">按钮</a>'
                }

                return result;
            },
        },
        {
            field: 'isnav',
            title: '导航菜单',
            formatter: function(value, row, index) {
                if(value == 0){
                    result = '<span class="badge badge-danger">否</span>'
                }else if (value == 1){
                    result = '<span class="badge badge-info">是</span>'
                }

                return result;
            },
        },
        {
            field: 'status',
            title: '状态',
            sortable: true,
            /*
             * 可以选择采用开关来处理状态显示
             * 或者采用上个示例的处理方式
             */
            formatter: function(value, row, index) {
                if (value == 0) {
                    is_checked = '';
                } else if (value == 1) {
                    is_checked = 'checked="checked"';
                }
                result = '<div class="custom-control custom-switch"><input type="checkbox" class="custom-control-input" id="customSwitch' + row.id + '" ' + is_checked + '><label class="custom-control-label" for="customSwitch' + row.id + '" onClick="updateStatus(' + row.id + ', ' + value + ')"></label></div>';

                return result;
            },
        },
        {
            field: 'create_time',
            title: '创建时间'
        },
        {
            field: 'operate',
            title: '操作',
            align: 'center',
            events: {
                'click .role-add': function(e, value, row, index) {
                    //add(row.id);
                },
                'click .role-delete': function(e, value, row, index) {
                    del(row.id);
                },
                'click .role-edit': function(e, value, row, index) {
                    //update(row.id);
                }
            },
            formatter: operateFormatter
        }
    ],

    responseHandler: function(res) {
        return {
            //"total": res.DATA.totalRecordCount,//总页数
            "rows": res.data   //数据
        };
    },

    treeShowField: 'name',
    parentIdField: 'pid',
    search:false,  //是否启用搜索框
    searchOnEnterKey:false,  //按回车触发搜索方法
    showRefresh: true,  //是否显示刷新按钮

    onResetView: function(data) {
        $treeTable.treegrid({
            initialState: 'collapsed', // 所有节点都折叠
            treeColumn: 1,
            //expanderExpandedClass: 'mdi mdi-folder-open',  // 可自定义图标样式
            //expanderCollapsedClass: 'mdi mdi-folder',
        });

        // 只展开树形的第一集节点
        //$treeTable.treegrid('getRootNodes').treegrid('expand');
    },
    onCheck: function(row) {
        var datas = $treeTable.bootstrapTable('getData');

        selectChilds(datas, row, 'id', 'pid', true); // 选择子类

        selectParentChecked(datas, row, 'id', 'pid'); // 选择父类

        $treeTable.bootstrapTable('load', datas);
    },

    onUncheck: function(row) {
        var datas = $treeTable.bootstrapTable('getData');
        selectChilds(datas, row, 'id', 'pid', false);
        $treeTable.bootstrapTable('load', datas);
    },
});

// 操作按钮
function operateFormatter(value, row, index) {
    return [
        '<a type="button" class="role-add btn btn-xs btn-default m-r-5" title="添加" data-toggle="modal" data-target="#exampleModalChange" data-zijie="'+row.id+'" data-toggle="tooltip"><i class="mdi mdi-plus"></i></a>',
        '<a type="button" class="role-add btn btn-xs btn-default m-r-5" title="修改" data-toggle="modal" data-target="#exampleModalChange" data-whatever="'+row.id+'" data-toggle="tooltip"><i class="mdi mdi-pencil"></i></a>',
        '<a type="button" class="role-delete btn btn-xs btn-default" title="删除" data-toggle="tooltip"><i class="mdi mdi-delete"></i></a>'
    ].join('');
}

/**
 * 选中父项时，同时选中子项
 * @param datas 所有的数据
 * @param row 当前数据
 * @param id id 字段名
 * @param pid 父id字段名
 */
function selectChilds(datas, row, id, pid, checked) {
    for (var i in datas) {
        if (datas[i][pid] == row[id]) {
            datas[i].check = checked;
            selectChilds(datas, datas[i], id, pid, checked);
        };
    }
}

function selectParentChecked(datas, row, id, pid) {
    for (var i in datas) {
        if (datas[i][id] == row[pid]) {
            datas[i].check = true;
            selectParentChecked(datas, datas[i], id, pid);
        };
    }
}

function post_submit() {
    $.ajax({
        //几个参数需要注意一下
        type: "POST",//方法类型
        dataType: "json",//预期服务器返回的数据类型
        url: "/admin/auth/post_submit" ,//url
        data: $('#form1').serialize(),
        success: function (res) {
            console.log(res);//打印服务端返回的数据(调试用)
            if (res.code === 0) {
                $.alert({
                    title: '成功',
                    icon: 'mdi mdi-alert',
                    type: 'blue',
                    content: res.msg,
                    buttons: {
                        okay: {
                            text: '确认',
                            btnClass: 'btn-blue',
                            action: function() {
                                $('#exampleModalChange').modal('hide');
                                $(".tree-table").bootstrapTable('refresh');
                            }
                        }
                    }
                });
            }else {
                $.alert({
                    title: '错误',
                    icon: 'mdi mdi-alert',
                    type: 'red',
                    content: res.msg,
                    buttons: {
                        okay: {
                            text: '确认',
                            btnClass: 'btn-blue',
                            action: function() {
                                //$('[alt="captcha"]').click();
                            }
                        }
                    }
                });
            };
        },
        error : function() {
            $.alert({
                title: '警告',
                content: '请检查返回是否正常！',
                icon: 'mdi mdi-access-point-network-off',
                animation: 'scale',
                closeAnimation: 'scale',
                buttons: {
                    okay: {
                        text: '确认',
                        btnClass: 'btn-blue'
                    }
                }
            });
        }
    });
}

function del(id) {
    $.confirm({
        title: '提示',
        content: '您确定要删除此节点？',
        icon: 'mdi mdi-alert',
        animation: 'scale',
        closeAnimation: 'zoom',
        buttons: {
            confirm: {
                text: '是的',
                btnClass: 'btn-orange',
                action: function() {
                    $.ajax({
                        //几个参数需要注意一下
                        type: "POST",//方法类型
                        dataType: "json",//预期服务器返回的数据类型
                        url: "/admin/auth/del" ,//url
                        data: {id: id},
                        success: function (res) {
                            console.log(res);//打印服务端返回的数据(调试用)
                            if (res.code === 0) {
                                $.alert({
                                    title: '成功',
                                    icon: 'mdi mdi-alert',
                                    type: 'blue',
                                    content: res.msg,
                                    buttons: {
                                        okay: {
                                            text: '确认',
                                            btnClass: 'btn-blue',
                                            action: function() {
                                                $(".tree-table").bootstrapTable('refresh');
                                            }
                                        }
                                    }
                                });
                            }else {
                                $.alert({
                                    title: '错误',
                                    icon: 'mdi mdi-alert',
                                    type: 'red',
                                    content: res.msg,
                                    buttons: {
                                        okay: {
                                            text: '确认',
                                            btnClass: 'btn-blue',
                                            action: function() {
                                                //$('[alt="captcha"]').click();
                                            }
                                        }
                                    }
                                });
                            };
                        },
                        error : function() {
                            $.alert({
                                title: '警告',
                                content: '请检查返回是否正常！',
                                icon: 'mdi mdi-access-point-network-off',
                                animation: 'scale',
                                closeAnimation: 'scale',
                                buttons: {
                                    okay: {
                                        text: '确认',
                                        btnClass: 'btn-blue'
                                    }
                                }
                            });
                        }
                    });
                }
            },
            '取消': function() {

            }
        }
    });

}

function updateStatus(id, state) {
    var newstate = (state == 1) ? 0 : 1; // 发送参数值跟当前参数值相反
    $.ajax({
        type: "get",
        url: "http://www.bixiaguangnian.com/index/test/testGridJson",
        data: {id: id, state: newstate},
        dataType: 'jsonp',
        success: function(data, status) {
            if (data.code == '200') {
                $treeTable.bootstrapTable('updateCellByUniqueId', {id: id, field: 'status', value: newstate});
            } else {
                alert(data.msg);
                $treeTable.bootstrapTable('updateCellByUniqueId', {id: id, field: 'status', value: state}); // 因开关点击后样式是变的，失败也重置下
            }
        },
        error: function() {
            alert('修改失败，请稍后再试');
        }
    });
}

function test() {
    var selRows = $treeTable.bootstrapTable("getSelections");
    if (selRows.length == 0) {
        alert("请至少选择一行");
        return;
    }
    console.log(selRows);

    var postData = "";
    $.each(selRows, function(i) {
        postData += this.id;
        if (i < selRows.length - 1) {
            postData += ",";
        }
    });
    $.confirm({
        title: '提示',
        content: '您确定要删除此节点？',
        icon: 'mdi mdi-alert',
        animation: 'scale',
        closeAnimation: 'zoom',
        buttons: {
            confirm: {
                text: '是的',
                btnClass: 'btn-orange',
                action: function() {
                    $.ajax({
                        //几个参数需要注意一下
                        type: "POST",//方法类型
                        dataType: "json",//预期服务器返回的数据类型
                        url: "/admin/auth/del" ,//url
                        data: {id:'',ids: postData},
                        success: function (res) {
                            console.log(res);//打印服务端返回的数据(调试用)
                            if (res.code === 0) {
                                $.alert({
                                    title: '成功',
                                    icon: 'mdi mdi-alert',
                                    type: 'blue',
                                    content: res.msg,
                                    buttons: {
                                        okay: {
                                            text: '确认',
                                            btnClass: 'btn-blue',
                                            action: function() {
                                                $(".tree-table").bootstrapTable('refresh');
                                            }
                                        }
                                    }
                                });
                            }else {
                                $.alert({
                                    title: '错误',
                                    icon: 'mdi mdi-alert',
                                    type: 'red',
                                    content: res.msg,
                                    buttons: {
                                        okay: {
                                            text: '确认',
                                            btnClass: 'btn-blue',
                                            action: function() {
                                                //$('[alt="captcha"]').click();
                                            }
                                        }
                                    }
                                });
                            };
                        },
                        error : function() {
                            $.alert({
                                title: '警告',
                                content: '请检查返回是否正常！',
                                icon: 'mdi mdi-access-point-network-off',
                                animation: 'scale',
                                closeAnimation: 'scale',
                                buttons: {
                                    okay: {
                                        text: '确认',
                                        btnClass: 'btn-blue'
                                    }
                                }
                            });
                        }
                    });
                }
            },
            '取消': function() {

            }
        }
    });
}